package net.xfok.tool;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;

import net.xfok.tool.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Ping extends Activity implements OnClickListener{
	private static final String TAG="xPing";
	private static final int BUFFER=4096; 
	private static final int COUNT=5;
	private static final String LOCAL="127.0.0.1";
	
	private TextView tv;
	private EditText et;
	private Button bt;
	BufferedReader bufferedreader ;
	InputStream is;
	InputStreamReader isReader;
	
    private String result="";
    private String command=null;
	private boolean change=true;
    private Timer timer=new Timer();
    private ProgressDialog progress = null;
	
    /** Called when the activity is first created. */
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv=(TextView)findViewById(R.id.text);
        et=(EditText)findViewById(R.id.host);
        bt=(Button)findViewById(R.id.btn_ping);
        bt.setOnClickListener(this);
        timer.schedule(task,0,1000);
    }
    
    public void onClick(View v) {
		switch(v.getId()){
			case R.id.btn_ping:
				String host=et.getText().toString(); 
				if(host==null||host.trim().equals("")){
					host=LOCAL;
				}
				try{
					ping(host);		
				}catch(Exception e){
					e.printStackTrace();
				}
		    	break;
		}  	
    }
    
    private void ping(String host){
    	command="ping -c "+COUNT+" "+host;   
    	result="";
    	Log.i(TAG, command);
    	this.progress = ProgressDialog.show(
	            this,
	            null,
	            getResources().getText(R.string.dialog_message_loading),
	            true
	        );
			AsyncTask<String, ProgressDialog, String[]> asyncTask = new AsyncTask<String, ProgressDialog, String[]>() {
		        protected String[] doInBackground(String... params) {				
					try {
				    	execCommand(command);   
			        } catch (Exception e) {
			            // TODO Auto-generated catch block   
			            e.printStackTrace();           
			        } 
			        return null;
		        }  
		        protected void onPostExecute(String[] result) {
		            if (Ping.this.progress!=null&&bufferedreader!=null) {
		            	Ping.this.progress.dismiss();       	
		            	Ping.this.progress = null;
//		            	if(!schedule){
//		            		timer.schedule(task,0,1000);
//		            	}
		            }
		        }
		    };
		    asyncTask.execute(null);
	}
    
    private void execCommand(String command){
		try{
		    Runtime runtime = Runtime.getRuntime();  
		    Process proc = runtime.exec(command);        
		    is = proc.getInputStream();
		    isReader = new InputStreamReader(is);
		    bufferedreader = new BufferedReader(isReader,BUFFER);
		    try {
		    	Log.i(TAG, "proc.waitFor()="+proc.waitFor());
		        if (proc.waitFor() != 0) {
		            Log.i(TAG,"exit value = " + proc.exitValue());
		        } 
		    }
		    catch (InterruptedException e) {  
		        Log.e(TAG, e.getMessage());
		    }
		}catch(Exception e){
			Log.e(TAG, e.getMessage());
		}
	}
    
    private String showText(){
    	String line = "";
    	StringBuilder sb = new StringBuilder(line);
    	try{  		 		     		   
 		    if((line = bufferedreader.readLine())!= null) {
 		    	Log.i(TAG, line);
 		        sb.append(line);
 		        sb.append('\n');
 		    }
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return sb.toString();	
    }
    
    Handler handler = new Handler(){  		  
        public void handleMessage(Message msg) {  
            switch (msg.what) {      
            case 1:      
            	if(change){
            		result+=showText();
            		change = false;
            		tv.setText(result);    
            	}else{
            		result+=showText();
            		change = true;
            		tv.setText(result);    
            	}  
                break;      
            }      
            super.handleMessage(msg);  
        }        
    };  
    
	TimerTask task = new TimerTask(){   
        public void run() {
        	Message message = new Message();      
            message.what = 1;      
            handler.sendMessage(message);   
	    } 
    };

}